package com.big_data_studio.fiter;

import com.alibaba.fastjson.JSON;
import com.big_data_studio.util.general.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 *  定义授权异常 ，继承 AccessDeniedHandler 接口
 *
 * @author : 曾小杰
 * @date : 2022-03-28 22:44
 **/

@Component
public class AuthAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException{
        //登陆状态下，权限不足执行该方法
        System.out.println("权限不足：" + e.getMessage());
        response.setStatus(403);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setContentType("multipart/form-data");
        PrintWriter printWriter = response.getWriter();
        printWriter.write(JSON.toJSONString(R.error("当前用户权限不足")));
        printWriter.flush();
    }
}
